package com.vcs.frm.service;

import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.vcs.frm.dao.JobseekerDao;
import com.vcs.frm.dao.common.CommonDao;
import com.vcs.frm.domain.Jobseeker;
import com.vcs.frm.domain.User;
import com.vcs.frm.domain.UserRole;
import com.vcs.frm.utils.Constants;

@Service
public class JobseekerServiceImpl implements JobseekerService {

	/* Logger object */
	private final Logger log = Logger.getLogger(this.getClass());

	@Autowired
	private JobseekerDao jobseekerDao;

	@Autowired
	private CommonDao commonDao;

	public void setJobseekerDao(JobseekerDao jobseekerDao) {
		this.jobseekerDao = jobseekerDao;
	}

	public void setCommonDao(CommonDao commonDao) {
		this.commonDao = commonDao;
	}

	@Override
	@Transactional
	public void saveJobseeker(Jobseeker jobseeker, String password) {

		/* Date when the record was created */
		jobseeker.setCreatedDate(new Date());
		jobseekerDao.saveJobseeker(jobseeker, password);
	}

	@Override
	@Transactional
	public Jobseeker getJobseekerByProfileId(Long profileId) {
		return jobseekerDao.getJobseekerByProfileId(profileId);
	}

	@Override
	@Transactional
	public Jobseeker getJobseekerProfileByUsername(String username) {

		log.info("inside getJobseekerProfileByUsername - Service layer");

		/* get user by username */
		User user = commonDao.getUserByUsername(username);
		log.info("User from Db : " + user);

		/*
		 * Check if logged-in user is a client or a jobseeker, accordingly load
		 * his profile
		 */
		log.info("........" + user.getUserRoles());

		Jobseeker js = null;
		for (UserRole r : user.getUserRoles()) {

			if (r.getAuthority().equalsIgnoreCase(Constants.ROLE_JOBSEEKER)) {

				/*
				 * Logged-in user is a client so load his profile from client
				 * table
				 */
				log.info("Logged-in user is Client.............");

				js = jobseekerDao.getJobseekerByProfileId(user.getUserId());

			}

		}
		log.info("leaving getJobseekerProfileByUsername - Service layer");
		return js;
	}

}
